import { useEffect, useState } from 'react';
import { getMicroAppManager, defaultHandleMessage } from './manager';
import type { MicroAppInitState } from './types';

/**
 * React Hook：iframe 子页面获取父页面下发的微应用状态（唯一推荐用法）
 * - 自动监听/解绑 postMessage
 * - 状态自动响应式更新
 * - 类型安全，极简
 */
export function useMicroAppState(): MicroAppInitState | undefined {
  const [state, setState] = useState<MicroAppInitState | undefined>(() => getMicroAppManager().getState());
  useEffect(() => {
    function handler(event: MessageEvent) {
      defaultHandleMessage(event);
      setState(getMicroAppManager().getState());
    }
    window.addEventListener('message', handler);
    return () => window.removeEventListener('message', handler);
  }, []);
  return state;
}

/**
 * 权限检查 Hook
 * @param codes string | string[] 需要检查的权限 code 或 code 数组
 * @returns boolean 是否有权限（任意一个 code 匹配即为 true）
 */
export function useAuthorityChecker(codes: string | string[]): boolean {
  const state = useMicroAppState();
  const authorityList = state?.data?.authorityList;
  if (!authorityList || authorityList.length === 0) return false;
  const codeArr = Array.isArray(codes) ? codes : [codes];
  // authorityList: string[][]，只要任意子数组包含任意 code 即为 true
  return codeArr.some(code => authorityList.some(arr => arr.includes(code)));
} 